package com.zhike.common.utils;

import java.io.InputStream;

import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.core.io.ClassPathResource;

import cn.hutool.core.io.IoUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class IpdbUtil {

    private static Searcher searcher;

    public static String getIpAddress(String ip) {
        ip = ip.replace("/", "");
        if ("127.0.0.1".equals(ip) || ip.startsWith("192.168")) {
            return "局域网";
        }
        if (searcher == null) {
            try {
                ClassPathResource resource = new ClassPathResource("ipdb/ip2region.xdb");
                InputStream inputStream = resource.getInputStream();
                byte[] bytes = IoUtil.readBytes(inputStream);
                searcher = Searcher.newWithBuffer(bytes);
            } catch (Exception e) {
                log.error("failed to create content cached searcher: ", e);
                return null;
            }
        }
        // 3、查询
        String region = null;
        try {
            log.debug("IP：{}", ip);
            region = searcher.search(removePort(ip));
        } catch (Exception e) {
            log.error("Get IP[{}] Addr, err: {}", removePort(ip), e.getMessage());
        }
        return region;
    }

    public static String removePort(String ipWithPort) {
        if (ipWithPort == null) {
            return null;
        }

        String[] parts = ipWithPort.split(":");
        return parts[0];
    }
}
